package com.anyou.mall.util;

import com.alibaba.fastjson.JSONObject;

import com.anyou.common.exception.GlobalException;
import com.anyou.mall.sho.vo.PostionVo;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.time.format.DateTimeFormatter;

/**
 * 腾讯地图地址解析成定位坐标工具类
 */
@Slf4j
public class QQmapUtil {

    private DateTimeFormatter dt0 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //腾讯地图定位服务密钥
    public static String MAP_AK = "U67BZ-QROLD-4H346-HRHOS-AACKS-6IBOU";

    //地址解析成定位坐标请求地址
    public static String MAP_URL = "http://apis.map.qq.com/ws/geocoder/v1/?output=json&key=" + MAP_AK;

    /**
     * 将经纬度获取解析成详细地址
     * @param lng 经度
     * @param lat 纬度
     * @return
     */
    public static String getAddress(double lng, double lat) {
        String address = "";
        String location = lat + "," + lng;
        BufferedReader in = null;
        URL url = null;
        URLConnection connection = null;
        try {
             url = new URL(MAP_URL + "&location=" + location);
            connection = url.openConnection();
            connection.setDoOutput(true);
            in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String line;
            StringBuilder text = new StringBuilder("");
            while ((line = in.readLine()) != null) {
                text.append(line.trim());
            }
            JSONObject result = JSONObject.parseObject(text.toString());
            if (result != null && result.getIntValue("status") == 0) {
                    address = result.getJSONObject("result").getString("formatted_address");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return address;
    }

    /**
     * 将地址解析成经纬度
     * @param address
     * 地址，例：浙江省杭州市西湖区
     * @return 返回经纬度数据。例：{"lng":120.08899292561351,"lat":30.207036169515438}
     * 返回值保留6位小数
     */
    public static PostionVo getPosition(String address) {
        BufferedReader in = null;
        URL url = null;
        URLConnection connection = null;
        try {
             url = new URL(MAP_URL + "&address=" + address);
            connection = url.openConnection();
            connection.setDoOutput(true);
            in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String line;
            StringBuilder text = new StringBuilder("");
            while ((line = in.readLine()) != null) {
                text.append(line.trim());
            }
            JSONObject result = JSONObject.parseObject(text.toString());
            log.info("腾讯地图将地址解析成经纬度的结果为:{}", result);
            if (result != null && result.getIntValue("status") == 0) {
                JSONObject location = result.getJSONObject("result").getJSONObject("location");
                double lng=location.getDoubleValue("lng");//经度
                double lat=location.getDoubleValue("lat");//纬度
                //处理超过6位小数的经度,只保留6位小数,5位可以精确到米
                lng=length6Value(lng);
                lat=length6Value(lat);
                PostionVo postionVo = new PostionVo(lat, lng);
                return postionVo;
            }else if(result != null && result.getIntValue("status") == 347){
                //腾讯返回的是'{"message":"查询无结果","status":347}'
                return null;
            }else{
                throw new GlobalException("腾讯地图将地址解析成经纬度,解析失败,腾讯返回结果为:"+result.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("腾讯地图将地址解析成经纬度,解析失败,错误信息为:"+e.getMessage());
        }

    }

    /**
     * 处理超过6位小数的经度,只保留6位小数,5位可以精确到米
     * @param lng
     * @return
     */
    private static double length6Value(double lng) {
        String str=lng+"";
        int dian = str.indexOf(".");
        String str0=str.substring(0,dian);
        String strlast=str.substring(dian+1,str.length());
        String str1="";
        if(strlast.length()>=6){
            str1= str.substring(dian+1,dian+6+1);
        }else{
            str1= str.substring(dian+1,str.length());
        }
        str=str0+"."+ str1;
       double res= Double.parseDouble(str);
        return res;
    }

    public static void main(String[] args) {
//        System.out.println(getAddress(120.08899292561351, 30.207036169515438));
//        System.out.println(getPosition("浙江省杭州市西湖区"));
        double v = length6Value(22.53785);
        double v2 = length6Value(114.0238);
        System.out.println(v);
        System.out.println(v2);
    }



}
